package cn.itsource.template;


import cn.hutool.http.HttpUtil;
import cn.itsource.config.WeChatConfig;
import cn.itsource.domain.OpenIdResult;
import cn.itsource.domain.PhoneInfo;
import cn.itsource.domain.PhoneResult;
import cn.itsource.domain.TokenResult;
import com.alibaba.fastjson.JSON;

/**
 * @program fccar
 * @Author luoc
 * @Date 2024/09/04 13:39
 * @Version 1.0.0
 * @Description
 */


public class WeChatTemplate {
    private WeChatConfig weChatConfig;

    public WeChatTemplate(WeChatConfig weChatConfig) {
        this.weChatConfig = weChatConfig;
    }

    public String getOpenId(String code){
        // 构造获取openId的url
        String url = String.format(WeChatConfig.WECHAT_URL, weChatConfig.getAppid(), weChatConfig.getSecret(), code);
        System.out.println("url = " + url);
        // 发送请求
        String res = HttpUtil.get(url);
        OpenIdResult openIdResult = JSON.parseObject(res, OpenIdResult.class);
        return openIdResult.getOpenid();
    }

    public String getPhoneNumber(String phoneCode){
        String url = String.format(WeChatConfig.TOKEN_URL, weChatConfig.getAppid(), weChatConfig.getSecret());
        String token = HttpUtil.get(url);
        TokenResult tokenResult = JSON.parseObject(token, TokenResult.class);
        String accessToken = tokenResult.getAccess_token();
        String phoneUrl = String.format(weChatConfig.PHONE_URL, accessToken);
        String res = HttpUtil.post(phoneUrl, phoneCode);
        PhoneResult phoneResult = JSON.parseObject(res, PhoneResult.class);
        PhoneInfo phoneInfo = JSON.parseObject(phoneResult.getPhoneInfo(), PhoneInfo.class);
        return phoneInfo.getPhoneNumber();
    }
}
